package com.it.smartoldb.controller;

import com.it.smartoldb.common.Result;
import com.it.smartoldb.repository.AppointmentRepository;
import com.it.smartoldb.repository.ElderlyRepository;
import com.it.smartoldb.repository.HealthRecordRepository;
import com.it.smartoldb.service.ElderlyService;
import com.it.smartoldb.service.HealthRecordService;
import com.it.smartoldb.service.StaffService;
import com.it.smartoldb.service.AppointmentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 仪表板控制器
 */
@Tag(name = "仪表板管理", description = "系统统计数据相关接口")
@RestController
@RequestMapping("/api/dashboard")
@RequiredArgsConstructor
public class DashboardController {
    
    private final ElderlyService elderlyService;
    private final HealthRecordService healthRecordService;
    private final StaffService staffService;
    private final AppointmentService appointmentService;
    
    // 添加Repository依赖
    private final HealthRecordRepository healthRecordRepository;
    private final AppointmentRepository appointmentRepository;
    private final ElderlyRepository elderlyRepository;
    
    /**
     * 获取仪表板统计数据
     */
    @Operation(summary = "获取仪表板统计数据", description = "获取系统各模块的统计数据")
    @GetMapping("/statistics")
    public Result<Map<String, Object>> getStatistics() {
        System.out.println("=== 调用仪表板统计数据接口 ===");
        Map<String, Object> statistics = new HashMap<>();
        
        // 获取各模块统计数据
        statistics.put("elderlyCount", elderlyService.getTotalCount());
        statistics.put("healthRecordCount", healthRecordService.getTotalCount());
        statistics.put("staffCount", staffService.getTotalCount());
        statistics.put("appointmentCount", appointmentService.getTotalCount());
        
        // 获取预约统计
        Map<String, Object> appointmentStats = appointmentService.getAppointmentStatistics();
        statistics.put("appointmentStats", appointmentStats);
        
        // 获取健康记录统计
        Map<String, Object> healthStats = healthRecordService.getStatistics();
        statistics.put("healthStats", healthStats);
        
        System.out.println("统计数据: " + statistics);
        return Result.success(statistics);
    }
    
    /**
     * 获取健康状态分布
     */
    @Operation(summary = "获取健康状态分布", description = "获取老人健康状态的分布统计")
    @GetMapping("/health-status")
    public Result<Map<String, Object>> getHealthStatusDistribution() {
        System.out.println("=== 调用健康状态分布接口 ===");
        Map<String, Object> distribution = healthRecordService.getStatistics();
        System.out.println("健康状态分布数据: " + distribution);
        return Result.success(distribution);
    }
    
    /**
     * 获取预约状态分布
     */
    @Operation(summary = "获取预约状态分布", description = "获取预约状态的分布统计")
    @GetMapping("/appointment-status")
    public Result<Map<String, Object>> getAppointmentStatusDistribution() {
        Map<String, Object> distribution = appointmentService.getAppointmentStatistics();
        return Result.success(distribution);
    }
    
    /**
     * 获取近7天健康记录趋势
     */
    @Operation(summary = "获取健康记录趋势", description = "获取近7天的健康记录数量趋势")
    @GetMapping("/health-trend")
    public Result<Map<String, Object>> getHealthRecordTrend() {
        System.out.println("=== 调用健康记录趋势接口 ===");
        Map<String, Object> trend = new HashMap<>();
        List<String> dates = new ArrayList<>();
        List<Integer> counts = new ArrayList<>();
        
        // 获取近7天的数据
        LocalDateTime startDate = LocalDateTime.now().minusDays(6).withHour(0).withMinute(0).withSecond(0);
        
        // 查询数据库获取真实数据
        List<Object[]> results = healthRecordRepository.countByDateRange(startDate);
        
        // 创建日期到数量的映射
        Map<String, Integer> dateCountMap = new HashMap<>();
        for (Object[] result : results) {
            String dateStr = result[0].toString();
            Long count = (Long) result[1];
            dateCountMap.put(dateStr, count.intValue());
        }
        
        // 生成近7天的日期，确保每一天都有数据（没有记录的日期显示0）
        for (int i = 6; i >= 0; i--) {
            LocalDate date = LocalDate.now().minusDays(i);
            String dateStr = date.toString();
            String displayDate = date.format(DateTimeFormatter.ofPattern("MM-dd"));
            
            dates.add(displayDate);
            counts.add(dateCountMap.getOrDefault(dateStr, 0));
        }
        
        trend.put("dates", dates);
        trend.put("counts", counts);
        
        System.out.println("健康记录趋势数据: " + trend);
        return Result.success(trend);
    }
    
    /**
     * 获取近7天预约趋势
     */
    @Operation(summary = "获取预约趋势", description = "获取近7天的预约数量趋势")
    @GetMapping("/appointment-trend")
    public Result<Map<String, Object>> getAppointmentTrend() {
        System.out.println("=== 调用预约趋势接口 ===");
        Map<String, Object> trend = new HashMap<>();
        List<String> dates = new ArrayList<>();
        List<Integer> counts = new ArrayList<>();
        
        // 获取近7天的数据
        LocalDateTime startDate = LocalDateTime.now().minusDays(6).withHour(0).withMinute(0).withSecond(0);
        
        // 查询数据库获取真实数据
        List<Object[]> results = appointmentRepository.countByDateRange(startDate);
        
        // 创建日期到数量的映射
        Map<String, Integer> dateCountMap = new HashMap<>();
        for (Object[] result : results) {
            String dateStr = result[0].toString();
            Long count = (Long) result[1];
            dateCountMap.put(dateStr, count.intValue());
        }
        
        // 生成近7天的日期，确保每一天都有数据（没有记录的日期显示0）
        for (int i = 6; i >= 0; i--) {
            LocalDate date = LocalDate.now().minusDays(i);
            String dateStr = date.toString();
            String displayDate = date.format(DateTimeFormatter.ofPattern("MM-dd"));
            
            dates.add(displayDate);
            counts.add(dateCountMap.getOrDefault(dateStr, 0));
        }
        
        trend.put("dates", dates);
        trend.put("counts", counts);
        
        System.out.println("预约趋势数据: " + trend);
        return Result.success(trend);
    }
    
    /**
     * 获取服务类型分布
     */
    @Operation(summary = "获取服务类型分布", description = "获取预约服务类型的分布统计")
    @GetMapping("/service-type")
    public Result<List<Map<String, Object>>> getServiceTypeDistribution() {
        System.out.println("=== 调用服务类型分布接口 ===");
        List<Map<String, Object>> distribution = new ArrayList<>();
        
        // 查询数据库获取真实数据
        List<Object[]> results = appointmentRepository.countByServiceType();
        
        // 服务类型映射（将英文转换为中文显示）
        Map<String, String> serviceTypeMap = new HashMap<>();
        serviceTypeMap.put("physical_exam", "体检");
        serviceTypeMap.put("nursing", "护理");
        serviceTypeMap.put("meal_delivery", "送餐");
        serviceTypeMap.put("cleaning", "清洁");
        serviceTypeMap.put("companionship", "陪伴");
        serviceTypeMap.put("medical_consultation", "医疗咨询");
        serviceTypeMap.put("rehabilitation", "康复训练");
        
        for (Object[] result : results) {
            String serviceType = (String) result[0];
            Long count = (Long) result[1];
            
            Map<String, Object> item = new HashMap<>();
            // 使用中文名称，如果映射不存在则使用原始值
            String displayName = serviceTypeMap.getOrDefault(serviceType, serviceType);
            item.put("name", displayName);
            item.put("value", count.intValue());
            distribution.add(item);
        }
        
        // 如果没有数据，返回空列表而不是模拟数据
        if (distribution.isEmpty()) {
            System.out.println("服务类型分布数据为空");
        }
        
        System.out.println("服务类型分布数据: " + distribution);
        return Result.success(distribution);
    }
    
    /**
     * 获取年龄分布统计
     */
    @Operation(summary = "获取年龄分布", description = "获取老人年龄分布统计")
    @GetMapping("/age-distribution")
    public Result<List<Map<String, Object>>> getAgeDistribution() {
        System.out.println("=== 调用年龄分布接口 ===");
        List<Map<String, Object>> distribution = new ArrayList<>();
        
        try {
            // 查询所有老人的年龄
            List<Integer> ages = elderlyRepository.findAllAges();
            System.out.println("查询到的年龄数据: " + ages);
            
            // 在Java中进行年龄分组统计
            Map<String, Integer> ageGroupCounts = new HashMap<>();
            ageGroupCounts.put("60-65岁", 0);
            ageGroupCounts.put("66-70岁", 0);
            ageGroupCounts.put("71-75岁", 0);
            ageGroupCounts.put("76-80岁", 0);
            ageGroupCounts.put("80岁以上", 0);
            
            for (Integer age : ages) {
                if (age >= 60 && age <= 65) {
                    ageGroupCounts.put("60-65岁", ageGroupCounts.get("60-65岁") + 1);
                } else if (age >= 66 && age <= 70) {
                    ageGroupCounts.put("66-70岁", ageGroupCounts.get("66-70岁") + 1);
                } else if (age >= 71 && age <= 75) {
                    ageGroupCounts.put("71-75岁", ageGroupCounts.get("71-75岁") + 1);
                } else if (age >= 76 && age <= 80) {
                    ageGroupCounts.put("76-80岁", ageGroupCounts.get("76-80岁") + 1);
                } else if (age > 80) {
                    ageGroupCounts.put("80岁以上", ageGroupCounts.get("80岁以上") + 1);
                }
            }
            
            System.out.println("年龄分组统计: " + ageGroupCounts);
            
            // 构建返回数据（只包含有数据的分组）
            String[] orderedGroups = {"60-65岁", "66-70岁", "71-75岁", "76-80岁", "80岁以上"};
            for (String group : orderedGroups) {
                int count = ageGroupCounts.get(group);
                if (count > 0) {
                    Map<String, Object> item = new HashMap<>();
                    item.put("name", group);
                    item.put("value", count);
                    distribution.add(item);
                }
            }
            
            System.out.println("最终年龄分布数据: " + distribution);
            
        } catch (Exception e) {
            System.err.println("年龄分布统计出错: " + e.getMessage());
            e.printStackTrace();
        }
        
        return Result.success(distribution);
    }
    
    /**
     * 获取最近活动
     */
    @Operation(summary = "获取最近活动", description = "获取系统最近的活动记录")
    @GetMapping("/recent-activities")
    public Result<List<Map<String, Object>>> getRecentActivities() {
        System.out.println("=== 调用最近活动接口 ===");
        List<Map<String, Object>> activities = new ArrayList<>();
        
        // 这里应该查询数据库获取真实数据，暂时使用模拟数据
        String[] contents = {
            "张三老人完成了今日体检",
            "李四老人预约了护理服务", 
            "王五老人的血压数据异常",
            "新增护理人员赵六",
            "马七老人取消了预约服务"
        };
        
        String[] types = {"success", "primary", "warning", "info", "danger"};
        
        for (int i = 0; i < contents.length; i++) {
            Map<String, Object> activity = new HashMap<>();
            activity.put("id", i + 1);
            activity.put("content", contents[i]);
            activity.put("time", LocalDateTime.now().minusHours(i).format(
                DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")));
            activity.put("type", types[i]);
            activities.add(activity);
        }
        
        System.out.println("最近活动数据: " + activities);
        return Result.success(activities);
    }
} 